<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>vs-tree2.0_结合worker+indexDb</title>
  <link rel="stylesheet" href="../dist/vs-tree.css">
  <link rel="stylesheet" href="./static/css/index.css">
</head>

<body>
  <p>此示例在github中速度受限，请下载代码到本地试验！！！，其中用时为忽略下载时间</p>
  <div>用时：<span id="usetime"></span></div>
  <input id="search" type="text" autocomplete="off" placeholder="输入关键字进行过滤">
  <div id="tree" class="tree-demo"></div>
  <button id="checked" type="button">获取选中元素</button>
  <script>
    var db;
    var objectStore;
    var request = window.indexedDB.open('vs-tree', 1);
    request.onsuccess = function (e) {
      db = e.target.result;

      if (db.objectStoreNames.contains('treeData')) {
        objectStore = db.transaction(['treeData'], 'readwrite').objectStore('treeData')
        var store = objectStore.get(1)
        store.onsuccess = function () {
          var data = store.result
          if (data) {
            console.timeEnd('create:data')
            init(data)
          } else {
            createWorker()
          }
        }
      }
    };
    request.onupgradeneeded = (e) => {
      db = e.target.result;
      if (!db.objectStoreNames.contains('treeData')) {
        db.createObjectStore('treeData', { keyPath: 'id' });
      }
    }
    console.time('create:data')
    function createWorker() {
      let worker = new Worker('./static/js/work.js');
      worker.onmessage = function (event) {
        var objectStore = db.transaction(['treeData'], 'readwrite').objectStore('treeData')
        objectStore.add(event.data)
        console.timeEnd('create:data')
        init(event.data)
        worker.terminate()
      }
    }
  </script>
  <script src="../dist/vs-tree.js"></script>
  <script>
    var tree;
    let umap = {}
    let infomap = {}
    let depts = []
    function init(data) {
      umap = data.umap
      infomap = data.infomap
      depts = data.depts
      const root = data.root
      console.time('render:tree');
      var time = Date.now()

      tree = new vsTree.default('#tree', {
        data: root[0],
        showCheckbox: true,
        max: 988,
        checkFilter: function (node) {
          return node.isLeaf
        },
        limitAlert: function () {
          alert('超过最大可选')
        },
        format: function (data) {
          var child = []
          if (data.obj === 'department') {
            child = depts.filter(v => v.obj === 'department' && v.data.pdid === data.data.did)
            child = child.concat(umap[data.data.did] || [])
            return {
              name: data.data.name || '---',
              children: child
            }
          }
          return {
            name: infomap[data.uid] && infomap[data.uid].name,
            isLeaf: true,
            children: []
          }
        },
        renderContent: function (h, node) {
          if (node.data.obj !== 'department') {
            return false
          }
          const count = getCount(umap, node)
          node.hasChildCount = count
          return h("div", {
            className: "tree-action",
            children: [
              h("span", {
                text: `（${count}）`
              })
            ]
          })
        }
      });
      console.timeEnd('render:tree');
      document.getElementById('usetime').innerHTML = Date.now() - time + 'ms'
    }

    function getCount(umap, node) {
      if (!umap[node.data.data.did]) return 0
      let count = 0
      const calc = (node) => {
        if (node.data.obj !== 'department') return
        count += (umap[node.data.data.did] && umap[node.data.data.did].length) || 0
        if (node.childNodes) {
          node.childNodes.forEach(v => {
            calc(v)
          })
        }
      }
      calc(node)
      return count
    }

    document.getElementById("checked").onclick = function () {
      console.log(tree);
      console.log(tree.getCheckedNodes());
    }

    document.getElementById('search').addEventListener('input', (e) => {
      tree.filter(e.target.value)
    })
  </script>
</body>

</html>